package Homework.cms.user;

import Homework.cms.user.Member;
import Homework.cms.util.JDBCHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MemberDao {
    //注册
    public static boolean register(Member member){
        boolean rs= JDBCHelper.add("insert into members(id,telephone,pwd,realname,email)"
                    + "values('" +member.getId()+"','"+member.getTelephone()+"','"+member.getPassword()+"','"+member.getTruename()
                    +"','" +member.getEmail()+"')");
        JDBCHelper.close();
        return rs;
    }
    //检查手机号是否已被注册
    public static Member check(String telephone){
        Member member=null;
        try {
            ResultSet rs= JDBCHelper.query("SELECT * FROM members WHERE telephone=?",telephone);
            if(rs!=null&&rs.next()){
                member=new Member();
                member.setTelephone(rs.getString("telephone"));
            }
        } catch (SQLException e) {
            System.out.println("查询手机号出错"+e.getMessage());
        } finally {
            JDBCHelper.close();
        }
        return member;
    }
    //登录
    public static Member login(String telephone, String pwd){
        Member member=null;
        try {
            ResultSet rs= JDBCHelper.query("SELECT * FROM members WHERE telephone=? and pwd=?",telephone,pwd);
            if(rs!=null&&rs.next()){
                member=new Member();
                member.setId(rs.getInt("id"));
                member.setTelephone(rs.getString("telephone"));
                member.setPassword(rs.getString("pwd"));
                member.setTruename(rs.getString("realname"));
                member.setEmail(rs.getString("email"));
                member.setTelephone(rs.getString("telephone"));
            }
        } catch (SQLException e) {
            System.out.println("登录出错"+e.getMessage());
        } finally {
            JDBCHelper.close();
        }
        return member;
    }

    public static List<Member> manage(){
        List<Member> members=new ArrayList<>();
        Member member=null;
        try {
            ResultSet rs= JDBCHelper.query("SELECT * FROM members");
            while(rs.next()){
                member=new Member();
                member.setId(rs.getInt("id"));
                member.setTelephone(rs.getString("telephone"));
                member.setPassword(rs.getString("pwd"));
                member.setTruename(rs.getString("realname"));
                member.setEmail(rs.getString("email"));
                member.setTelephone(rs.getString("telephone"));
                members.add(member);
            }
        } catch (SQLException e) {
            System.out.println("查询出错"+e.getMessage());
        } finally {
            JDBCHelper.close();
        }
        return members;
    }

}
